package com.caszx.chargingpile.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ScrollView;

import com.alibaba.fastjson.JSONException;
import com.app.base.adapter.CommonViewPageAdapter;
import com.app.base.adapter.RecyclerviewHorizontalAdapter;
import com.app.base.app.BaseNetViewActivity;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.jsonparse.JSONParse;
import com.app.utils.DiskUser;
import com.app.view.PagerSlidingTabStrip;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.entity.EntityStation;
import com.caszx.chargingpile.entity.EntityTabStationDetail;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.fragment.station.TabCommentFragment;
import com.caszx.chargingpile.fragment.station.TabDetailFragment;
import com.caszx.chargingpile.fragment.station.TabListFragment;
import com.caszx.chargingpile.fragment.station.TabPlansFeeFragment;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.rey.material.app.DialogFragment;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import github.chenupt.dragtoplayout.DragTopLayout;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

public class StationDetailActivity extends BaseTopBarNetActivity {

    private String stationId;
    private DragTopLayout dragLayout;

    private List<Fragment> pagers = new ArrayList<Fragment>(4);
    private CommonViewPageAdapter mAdapter;
    private ViewPager viewpager;
    private PagerSlidingTabStrip viewpageTabs;


    private RecyclerView mRecyclerView;
    private RecyclerviewHorizontalAdapter mHorizontalAdapter;
    private MenuItem menuLike;

    private ViewPager mViewpage;
    private Animator mCurrentAnimator;
    private float startScale;
    private Rect startBounds;
    private float startScaleFinal;
    private int mShortAnimationDuration = 300;
    private String[] mImageUrls;


    //详情
    private EntityTabStationDetail mEntityTabStationDetail;
    //计费方案
    private String stringFeeScheme;
    //电桩
    private String stringPlieList;
    //评论
    private String stringComment;

    private boolean isLike = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void init() {
        stationId = getIntent().getStringExtra("ID");
    }

    @Override
    protected void onLoad() {
        loadDetail();
    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.activity_station_detail, getContentView(), true);
        findView(view);
        initRecyclerView(view);
        initViewImagePage(view);
        initViewPage(view);
        return view;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_like, menu);
        menuLike = menu.findItem(R.id.menulike);
        changeLike(isLike);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (getBaseLoadedView(true) != null) {
            addCommStation(stationId, isLike);
        }

        return super.onOptionsItemSelected(item);
    }

    private void changeLike(boolean islike) {
        if (menuLike == null) return;
        menuLike.setIcon(islike ? R.mipmap.like_green : R.mipmap.like_gray);
    }


    private void addCommStation(String id, final boolean isCancel) {
        if (isCancel) {
            showProgressDialog("取消中...");
        } else {
            showProgressDialog("添加中...");
        }
        HashMap<String, String> params = new HashMap<>();
        String token = DiskUser.getStringValueByKey(this, "token");
        params.put("stationId", stationId);
        params.put("token", token);
        String url = isCancel ? ConstantUrl.URL_USER_CANCEL_STATION_ : ConstantUrl.URL_USER_ADD_STATION_;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(StationDetailActivity.this, getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code == -100) {
                                DialogHelp.showDialogOnlyMesg(StationDetailActivity.this, getResources().getString(R.string.error_minus_100), new DialogHelp.DialogActionClickListener() {
                                    @Override
                                    public void onPositiveActionClicked(DialogFragment fragment) {
                                        Intent intent = new Intent(StationDetailActivity.this, UserSignInActivity.class);
                                        startActivity(intent);
                                    }

                                    @Override
                                    public void onNegativeActionClicked(DialogFragment fragment) {
                                    }
                                });
                                return;
                            }

                            if (code < 0) {
                                //error
                                SnackbarHelp.showSnackbarMsg(StationDetailActivity.this, resultJsonObject.optString("msg"));
                            } else {
                                changeLike(!isCancel);
                                isLike = !isLike;
                                EventBus.getDefault().post(EventBusAction.ACTION_CHANGE_ADD_COMM_SATION);
                            }
                        }
                    }
                });

    }


    private void loadDetail() {
        HashMap<String, String> params = new HashMap<>();
        String token = DiskUser.getStringValueByKey(this, "token");
        params.put("stationId", stationId);
        params.put("token", token);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_STATION_DETAIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                DialogHelp.showDialogOnlyMesg(StationDetailActivity.this, resultJsonObject.optString("msg"), null);
                                showErrorView();
                            } else {
                                parserDetail(response);
                                parserImage(response);
                                //1、收藏 0、没收藏
                                int isStoreUp = response.optInt("isStoreUp");
                                stringFeeScheme = response.optString("feeScheme");
                                stringPlieList = response.optString("plieList");
                                stringComment = response.optString("commentList");
                                showContentView();
                                isLike = isStoreUp == 1 ? true : false;
                                changeLike(isLike);
                                if (mImageUrls == null) mRecyclerView.setVisibility(View.GONE);
                            }
                        }
                    }
                });
    }

    // Handle scroll event from fragments
    public void onEvent(Boolean b) {
        dragLayout.setTouchMode(b);
    }

    private void findView(View view) {
        dragLayout = (DragTopLayout) view.findViewById(R.id.drag_layout);
    }

    private void initViewPage(View view) {

        TabDetailFragment tab_01 = TabDetailFragment.newInstance(mEntityTabStationDetail);
        TabPlansFeeFragment tab_02 = TabPlansFeeFragment.newInstance(stringFeeScheme);
        TabListFragment tab_03 = TabListFragment.newInstance(stringPlieList);
//        TabCommentFragment tab_04 = TabCommentFragment.newInstance(stringComment);
        pagers.add(tab_01);
        pagers.add(tab_02);
        pagers.add(tab_03);
//        pagers.add(tab_04);


        viewpager = (ViewPager) view.findViewById(R.id.viewpager);
        viewpager.setOffscreenPageLimit(pagers.size());
        mAdapter = new CommonViewPageAdapter(getSupportFragmentManager());

        String[] tabs = getResources().getStringArray(R.array.station_detail_tab);
        mAdapter.setPageTitles(tabs);
        viewpager.setAdapter(mAdapter);
        mAdapter.setData(pagers);
        viewpageTabs = (PagerSlidingTabStrip) view.findViewById(R.id.indicator_tab);
        setTabsValue(viewpager);

        viewpageTabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                dragLayout.closeTopView(true);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    private void parserDetail(JSONObject jsonObject) {
        if (jsonObject == null) return;
        mEntityTabStationDetail = new EntityTabStationDetail();
        mEntityTabStationDetail.name = jsonObject.optString("stationName");
        mEntityTabStationDetail.address = jsonObject.optString("address");
        mEntityTabStationDetail.code = jsonObject.optString("stationCode");
        mEntityTabStationDetail.fast = jsonObject.optInt("fastRuningPile");
        mEntityTabStationDetail.slow = jsonObject.optInt("slowRuningPile");
        mEntityTabStationDetail.createDate = jsonObject.optInt("createDate");
        setCenterTitle(mEntityTabStationDetail.name);
    }

    private void parserImage(JSONObject jsonObject) {
        if (jsonObject == null) return;
        String str_image = jsonObject.optString("image");
        if (TextUtils.isEmpty(str_image)) {
            return;
        }
        if (!str_image.contains(",")) {
            mImageUrls = new String[1];
            mImageUrls[0] = str_image;
        } else {
            mImageUrls = str_image.split(",");
        }

    }


    protected void setTabsValue(ViewPager viewpage) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        viewpageTabs.setViewPager(viewpage);
        // 设置Tab是自动填充满屏幕的
        viewpageTabs.setShouldExpand(true);
        // 设置Tab的分割线是透明的
        viewpageTabs.setDividerColor(Color.TRANSPARENT);
        // 设置Tab底部线的高度
        viewpageTabs.setUnderlineHeight((int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 1, dm));
        // 设置Tab Indicator的高度
        viewpageTabs.setIndicatorHeight((int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 2, dm));
        // 设置Tab标题文字的大小
        viewpageTabs.setTextSize((int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 14, dm));
        // 设置Tab Indicator的颜色
        viewpageTabs.setIndicatorColor(getResources().getColor(R.color.colorAccent));
        // 设置选中Tab文字的颜色
        viewpageTabs.setSelectedTextColor(getResources().getColor(R.color.colorAccent));
        // 取消点击Tab时的背景色
        viewpageTabs.setTabBackground(0);
    }

    private void initRecyclerView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewPics);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerView.setLayoutManager(layoutManager);
        mHorizontalAdapter = new RecyclerviewHorizontalAdapter(this);
        mHorizontalAdapter.setOnItemClickListener(new RecyclerviewHorizontalAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                zoomImageFromThumb(view, position);
            }
        });
        mRecyclerView.setAdapter(mHorizontalAdapter);
        mHorizontalAdapter.setDatas(mImageUrls);
    }

    private void initViewImagePage(View view) {
        mViewpage = (ViewPager) view.findViewById(R.id.viewpageImage);
        mViewpage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                if (arg0 >= layoutManager.findLastVisibleItemPosition()) {
                    mRecyclerView.scrollToPosition(arg0);
                }
                if (arg0 <= layoutManager.findFirstVisibleItemPosition()) {
                    mRecyclerView.scrollToPosition(arg0);
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }


    private void zoomImageFromThumb(View thumbView, int position) {
        if (mCurrentAnimator != null) {
            mCurrentAnimator.cancel();
        }
        if (mViewpage.getAdapter() == null) {
            mViewpage.setAdapter(new SamplePagerAdapter(mImageUrls, this, mRecyclerView));
        }
        mViewpage.setCurrentItem(position, false);
        startBounds = new Rect();
        final Rect finalBounds = new Rect();
        final Point globalOffset = new Point();
        thumbView.getGlobalVisibleRect(startBounds);
        rootView.getGlobalVisibleRect(finalBounds, globalOffset);
        startBounds.offset(-globalOffset.x, -globalOffset.y);
        finalBounds.offset(-globalOffset.x, -globalOffset.y);

        if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds
                .width() / startBounds.height()) {
            // Extend start bounds horizontally
            startScale = (float) startBounds.height() / finalBounds.height();
            float startWidth = startScale * finalBounds.width();
            float deltaWidth = (startWidth - startBounds.width()) / 2;
            startBounds.left -= deltaWidth;
            startBounds.right += deltaWidth;
        } else {
            // Extend start bounds vertically
            startScale = (float) startBounds.width() / finalBounds.width();
            float startHeight = startScale * finalBounds.height();
            float deltaHeight = (startHeight - startBounds.height()) / 2;
            startBounds.top -= deltaHeight;
            startBounds.bottom += deltaHeight;
        }

        mViewpage.setVisibility(View.VISIBLE);
        AnimatorSet animSet = new AnimatorSet();
        animSet.setDuration(1);
        animSet.play(ObjectAnimator.ofFloat(mViewpage, "pivotX", 0f))
                .with(ObjectAnimator.ofFloat(mViewpage, "pivotY", 0f))
                .with(ObjectAnimator.ofFloat(mViewpage, "alpha", 1.0f));
        animSet.start();

        AnimatorSet set = new AnimatorSet();
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(dragLayout, "alpha", 1.0f, 0.f);
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mViewpage, "x",
                startBounds.left, finalBounds.left);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mViewpage, "y",
                startBounds.top, finalBounds.top);
        ObjectAnimator animatorScaleX = ObjectAnimator.ofFloat(mViewpage,
                "scaleX", startScale, 1f);
        ObjectAnimator animatorScaleY = ObjectAnimator.ofFloat(mViewpage,
                "scaleY", startScale, 1f);

        set.play(alphaAnimator).with(animatorX)
                .with(animatorY).with(animatorScaleX).with(animatorScaleY);
        set.setDuration(mShortAnimationDuration);
        set.setInterpolator(new DecelerateInterpolator());
        set.addListener(new AnimatorListenerAdapter() {

            public void onAnimationEnd(Animator animation) {
                mCurrentAnimator = null;
            }

            public void onAnimationCancel(Animator animation) {
                mCurrentAnimator = null;
            }
        });
        set.start();
        mCurrentAnimator = set;
        startScaleFinal = startScale;

    }

    private boolean getScaleFinalBounds(int position, RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView
                .getLayoutManager();
        View childView = layoutManager.findViewByPosition(position);
        startBounds = new Rect();
        final Rect finalBounds = new Rect();
        final Point globalOffset = new Point();

        if (childView == null) {
        } else {
            childView.getGlobalVisibleRect(startBounds);
        }

        rootView.getGlobalVisibleRect(finalBounds, globalOffset);
        startBounds.offset(-globalOffset.x, -globalOffset.y);
        finalBounds.offset(-globalOffset.x, -globalOffset.y);

        if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds
                .width() / startBounds.height()) {
            startScale = (float) startBounds.height() / finalBounds.height();
            float startWidth = startScale * finalBounds.width();
            float deltaWidth = (startWidth - startBounds.width()) / 2;
            startBounds.left -= deltaWidth;
            startBounds.right += deltaWidth;
        } else {
            startScale = (float) startBounds.width() / finalBounds.width();
            float startHeight = startScale * finalBounds.height();
            float deltaHeight = (startHeight - startBounds.height()) / 2;
            startBounds.top -= deltaHeight;
            startBounds.bottom += deltaHeight;
        }
        startScaleFinal = startScale;
        return true;
    }

    /**
     * ViewPage的适配器
     */
    private class SamplePagerAdapter extends PagerAdapter {

        private String[] mImageUrls;
        private Context mContext;
        private RecyclerView recyclerView;

        public SamplePagerAdapter(String[] mImageUrls, Context context, RecyclerView recyclerView) {
            this.mImageUrls = mImageUrls;
            this.mContext = context;
            this.recyclerView = recyclerView;
        }

        @Override
        public int getCount() {
            if (mImageUrls == null) return 0;
            return mImageUrls.length;
        }

        @Override
        public View instantiateItem(ViewGroup container, final int position) {
            final PhotoView photoView = new PhotoView(mContext);

            Picasso.with(mContext)
                    .load(mImageUrls[position])
                    .error(R.drawable.bitmap_error_picasso)
                    .placeholder(R.drawable.bitmap_error_picasso)
                    .config(Bitmap.Config.RGB_565)
                    .into(photoView);

            container.addView(photoView, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.MATCH_PARENT);
            photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                public void onPhotoTap(View paramAnonymousView,
                                       float paramAnonymousFloat1,
                                       float paramAnonymousFloat2) {
                    if (mCurrentAnimator != null) {
                        mCurrentAnimator.cancel();
                    }
//                             photoView.clearZoom();
                    boolean scaleResult = getScaleFinalBounds(position, recyclerView);
                    AnimatorSet as = new AnimatorSet();
                    ObjectAnimator containAlphaAnimator = ObjectAnimator.ofFloat(dragLayout, "alpha", 0.f, 1.0f);

                    if (scaleResult) {
                        ObjectAnimator animatorX = ObjectAnimator
                                .ofFloat(mViewpage, "x",
                                        startBounds.left);
                        ObjectAnimator animatorY = ObjectAnimator
                                .ofFloat(mViewpage, "y",
                                        startBounds.top);
                        ObjectAnimator animatorScaleX = ObjectAnimator
                                .ofFloat(mViewpage, "scaleX",
                                        startScaleFinal);
                        ObjectAnimator animatorScaleY = ObjectAnimator
                                .ofFloat(mViewpage, "scaleY",
                                        startScaleFinal);

                        as.play(containAlphaAnimator)
                                .with(animatorX).with(animatorY)
                                .with(animatorScaleX)
                                .with(animatorScaleY);
                    } else {
                        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mViewpage, "alpha", 0.1f);
                        as.play(alphaAnimator).with(containAlphaAnimator);
                    }
                    as.setDuration(mShortAnimationDuration);
                    as.setInterpolator(new DecelerateInterpolator());
                    as.addListener(new AnimatorListenerAdapter() {

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mViewpage.clearAnimation();
                            mViewpage.setVisibility(View.GONE);
                            mCurrentAnimator = null;
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            mViewpage.clearAnimation();
                            mViewpage.setVisibility(View.GONE);
                            mCurrentAnimator = null;
                        }
                    });
                    as.start();
                    mCurrentAnimator = as;

                }
            });

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
